$(document).ready(function() {
	
	//初始化按钮
	$("button").button();
	//初始不显示操作按钮
	$("#clear_button,#allbook_button,#test_button,#load_button").hide();
	//记录登录状态
	$("#login_button").data("isLogin",false);	
	//设置登录部门号为0
	$("#login_button").data("duty",0);	
	
	//对所有的按钮都显示busy
	$("#clear_button,#allbook_button,#test_button,#load_button").bind("mouseup",function(){
			　//显示“busy”
			  var busy=$(this).busy();
			  setTimeout(function(){
					busy.busy("hide");  
			   },1000);
	});
	
	$("#test_button").click(function(){
		//获取数据
		initSelect();
		
		//itest
		//alert($("#calendar").weekCalendar("serializeEvents"));
		
	});
		
    //初始化下拉选择框
    initSelect();


	//设置渐入渐出时间
	var timeIn=2000;
	var timeOut=4000;
	
	//记录下拉框选中的房间号（也就是表格名）
	var tbname=$("#selectRoom").find("option:selected").text();
	//将选择的表名存储起来
	$("#selectRoom").data("tbname",tbname);
	showInformation("默认选择的教室为："+tbname,timeIn,timeOut);
	
	
	
	//当选项改变时
	$("#selectRoom").change(function(){
		//将改变的选项保存到变量中
		$("#selectRoom").data("tbname",$("#selectRoom").find("option:selected").text());
		//先在前端清空所有的预约
		$("#calendar").weekCalendar("clear");
		
		//重新载入预约表,要同步
		talkWithServer("load",$("#selectRoom").data("tbname"),2,0,false,function(data){
				for(i=0;i<data.length;i++)
				{
					$("#calendar").weekCalendar("updateEvent",data[i]);
				}
				var str="你选择的教室为："+$("#selectRoom").data("tbname");
				showInformation(str,timeIn,timeOut);	
		});		
	});
	
	
	//增加教室
	$("#addRoom").click(function(){
		//用ID选择器不行，最好使用input:text选择
		var roomNum=$("input:text").val();
		
		//
		var reg=/^[1-9]{1,2}-[0-9]*$/;
		if(reg.test(roomNum))
		{		  				
			//不重复添加下拉框选项
			for(var j=0;j<$("#selectRoom option").length;j++)
			{
				if($("#selectRoom option:eq("+j+")").val()==roomNum)
				{
					alert("此项已经存在，不能添加");
					return;
				}
			}
			$("<option value='"+roomNum+"'>"+roomNum+"</option>").appendTo("#selectRoom")//添加下拉框的option
			//同时在数据库里创建新表
			talkWithServer("createTable",roomNum,2,0,false,function(data){
				showInformation("成功新建一个教室预定表！<br />"+data,timeIn,timeOut);		
			});
		}
		else
		{
			alert("输入格式不正确，请看“关于”内容");
		}
		//马上清空输入框
		$("input:text").val("");		
	});
	
	
		
   var $calendar = $('#calendar');   
   var id = getMaxID();

   $calendar.weekCalendar({
      displayOddEven:true,
      timeslotsPerHour : 4,
      //allowCalEventOverlap : true,
      //overlapEventsSeparate: true,
	  timeslotHeight:30,
      firstDayOfWeek : 1,
	  scrollToHourMillis:1500,
	  use24Hour:true,
	  dateFormat:"Y-M-d",
	  timeFormat:"H:i",
      businessHours :{start: 8, end: 23, limitDisplay: true },
      daysToShow : 7,
      switchDisplay: {'当天': 1, '3天': 3, '工作日': 5, '整周': 7},
	  newEventText:"创建新日程",
	  shortMonths:['1','2','3','4','5','6','7','8','9','10','11','12'],
	  longMonths:['一月','二月','三月','四月','五月','六月','七月','八月','九月','十月','十一月','十二月'],
	  longDays:['星期天','星期一','星期二','星期三','星期四','星期五','星期六'],	  
	  
      title: function(daysToShow) {
			return daysToShow == 1 ? '%date%' : '%start%<---->%end%';
      },
      height : function($calendar) {
         return $(window).height() - $("h1").outerHeight() - 1;
      },
      eventRender : function(calEvent, $event) {
		  
		  //如果不是本部门
		 if(calEvent.duty!= $("#login_button").data("duty"))
		 {
			 $event.css("backgroundColor","#C1D31B");
			 $event.find(".wc-time").css({
				 	"backgroundColor":"#BED112",
					"border":"2px dashed #1232D1" ,
				 });
			 $event.find(".wc-title").css({
				 	"color":"#F95A36"
				 });
		 }
		 
		 //过期事件
         if (calEvent.end.getTime() < new Date().getTime()) {
            $event.css("backgroundColor", "#aaa");
            $event.find(".wc-time").css({
               "backgroundColor" : "#999",
               "border" : "1px solid #888"
            });
         }
      },
	  
	  eventAfterRender:function(calEvent,$event){
		 if(!$("#login_button").data("isLogin"))
		 {
			 $calendar.weekCalendar("removeUnsavedEvents");
		 }  
	  },
      draggable : function(calEvent, $event) {
		  //只有同一个部门的人才可以拖动
         return calEvent.duty == $("#login_button").data("duty");
      },
      resizable : function(calEvent, $event) {
         return calEvent.duty == $("#login_button").data("duty");
      },
      eventNew : function(calEvent, $event) {
		  
		  if(!$("#login_button").data("isLogin"))
		  {
			  return;
		　　}
		  
         var $dialogContent = $("#event_edit_container");
         resetForm($dialogContent);
         var startField = $dialogContent.find("select[name='start']").val(calEvent.start);
         var endField = $dialogContent.find("select[name='end']").val(calEvent.end);
         var titleField = $dialogContent.find("input[name='title']");
         var bodyField = $dialogContent.find("textarea[name='body']");


         $dialogContent.dialog({
            modal: true,
            title: "新建预约",
            close: function() {
               $dialogContent.dialog("destroy");
               $dialogContent.hide();
               $('#calendar').weekCalendar("removeUnsavedEvents");
            },
            buttons: {
               "保存" : function() {
                  calEvent.id = id;
                  id++;
                  calEvent.start = new Date(startField.val());
                  calEvent.end = new Date(endField.val());
                  calEvent.title = titleField.val();
                  calEvent.body = bodyField.val();
				  calEvent.duty = $("#login_button").data("duty");

				  //如果时间大于两个小时则不保存,getTime返回是毫秒数，两个小时是7200000		  
				  if(calEvent.end.getTime()-calEvent.start.getTime()>7200050)
				  {
					  showInformation("操作不成功<br />注意：设定时间不能大于两个小时！",timeIn,timeOut);
					  return;
				  }

                  $calendar.weekCalendar("removeUnsavedEvents");
                  $calendar.weekCalendar("updateEvent", calEvent);
                  $dialogContent.dialog("close");

				//与服务器通话，保存新建的预约到浏览器
				//首先获取表名
				
				//测试console.dir(calEvent);
				
				//插入数据
				 talkWithServer("insert",$("#selectRoom").data("tbname"),$("#login_button").data("duty"),JSON.stringify(calEvent),true,function(data){
					 	showInformation(data,timeIn,timeOut);
						//刷新视图
						$("#calendar").weekCalendar("refresh");							
				 });			   
 
               },
               "取消" : function() {
                  $dialogContent.dialog("close");
               }
            }
         }).show();

         $dialogContent.find(".date_holder").text($calendar.weekCalendar("formatDate", calEvent.start));
         setupStartAndEndTimeFields(startField, endField, calEvent, $calendar.weekCalendar("getTimeslotTimes", calEvent.start));

      },
      eventDrop : function(calEvent, $event) {
		 //与服务器通话，更新数据库中的预约
		 talkWithServer("update",$("#selectRoom").data("tbname"),$("#login_button").data("duty"),JSON.stringify(calEvent),true,function(data){
				showInformation(data,timeIn,timeOut);
		 });
        
      },
      eventResize : function(calEvent, $event) {
		  
		　//如果时间大于两个小时则不保存,getTime返回是毫秒数，两个小时是7200000		  
		  if(calEvent.end.getTime()-calEvent.start.getTime()>7200050)
		  {
			  showInformation("拖曳操作不成功！<br />注意：设定时间不能大于两个小时！",timeIn,timeOut);		 
			  
		  }
		  else
		  {
			  //console.log(calEvent.start);
			  //console.log(calEvent.end);
			 //与服务器通话，更新数据库中的预约
			 talkWithServer("update",$("#selectRoom").data("tbname"),$("#login_button").data("duty"),JSON.stringify(calEvent),true,function(data){
					showInformation(data,timeIn,timeOut);
			 });
		  }
		  
		  //重新刷新视图
		   $("#calendar").weekCalendar("refresh");		  
      },
      eventClick : function(calEvent, $event) {

         if (calEvent.readOnly) {
            return;
         }
		 
		 if(!$("#login_button").data("isLogin"))
		 {
			 return;
		 }
		 
		 //如果不是当前部门，也返回
		 if(calEvent.duty!=$("#login_button").data("duty"))
		 {
			 return;
		 }

         var $dialogContent = $("#event_edit_container");
         resetForm($dialogContent);
         var startField = $dialogContent.find("select[name='start']").val(calEvent.start);
         var endField = $dialogContent.find("select[name='end']").val(calEvent.end);
         var titleField = $dialogContent.find("input[name='title']").val(calEvent.title);
         var bodyField = $dialogContent.find("textarea[name='body']");
         bodyField.val(calEvent.body);

         $dialogContent.dialog({
            modal: true,
            title: "编辑 - " + calEvent.title,
            close: function() {
               $dialogContent.dialog("destroy");
               $dialogContent.hide();
               $('#calendar').weekCalendar("removeUnsavedEvents");
            },
            buttons: {
               "保存" : function() {

                  calEvent.start = new Date(startField.val());
                  calEvent.end = new Date(endField.val());
                  calEvent.title = titleField.val();
                  calEvent.body = bodyField.val();
				  calEvent.duty = $("#login_button").data("duty");
				  
				  console.log(calEvent.end.getTime()-calEvent.start.getTime());
				  //如果时间大于两个小时则不保存,getTime返回是毫秒数，两个小时是7200000		  
				  if(calEvent.end.getTime()-calEvent.start.getTime()>7200050)
				  {
					  showInformation("操作不成功！<br />注意：设定时间不能大于两个小时！",timeIn,timeOut);
					  return;
				  }
				  

                  $calendar.weekCalendar("updateEvent", calEvent);
                  $dialogContent.dialog("close");
				 　//console.dir(calEvent);
				 //与服务器通话，更新数据库中的预约
				 talkWithServer("update",$("#selectRoom").data("tbname"),$("#login_button").data("duty"),JSON.stringify(calEvent),true,function(data){
					 	showInformation(data,timeIn,timeOut);
				});			  
               },
               "删除" : function() {
                  $calendar.weekCalendar("removeEvent", calEvent.id);
                  $dialogContent.dialog("close");

				//与服务器通话，保持数据同步
				 talkWithServer("delete",$("#selectRoom").data("tbname"),2,JSON.stringify(calEvent),true,function(data){
					 	showInformation(data,timeIn,timeOut);
				 });			  
               },
               "取消" : function() {
                  $dialogContent.dialog("close");
               }
            }
         }).show();

         var startField = $dialogContent.find("select[name='start']").val(calEvent.start);
         var endField = $dialogContent.find("select[name='end']").val(calEvent.end);
         $dialogContent.find(".date_holder").text($calendar.weekCalendar("formatDate", calEvent.start));
         setupStartAndEndTimeFields(startField, endField, calEvent, $calendar.weekCalendar("getTimeslotTimes", calEvent.start));
         $(window).resize().resize(); //fixes a bug in modal overlay size ??

      },
      eventMouseover : function(calEvent, $event) {
      },
      eventMouseout : function(calEvent, $event) {
      },
      noEvents : function() {

      },
/* 	  data:{
		  events:[
		  		{"id":1, "start":"2012-02-25T20:15:00.000+10:00", "end":"2012-02-25T21:15:00.000+10:00", "title":"Lunch with Mike"},
		   		{"id":2,"start":"2012-02-26T19:15:00.000+10:00", "end":"2012-02-26T20:15:00.000+10:00", "title":"Dev Meeting"}
		  	]
	  }*/
     data : function(start, end, callback) {
         callback(getEventData());
      }
   });

   function resetForm($dialogContent) {
      $dialogContent.find("input").val("");
      $dialogContent.find("textarea").val("");
   }

	function getEventData()
	{
		initEventData();
		return $("#calendar").data("initData");
	}

   /*
    * Sets up the start and end time fields in the calendar event
    * form for editing based on the calendar event being edited
    */
   function setupStartAndEndTimeFields($startTimeField, $endTimeField, calEvent, timeslotTimes) {

      $startTimeField.empty();
      $endTimeField.empty();

      for (var i = 0; i < timeslotTimes.length; i++) {
         var startTime = timeslotTimes[i].start;
         var endTime = timeslotTimes[i].end;
         var startSelected = "";
         if (startTime.getTime() === calEvent.start.getTime()) {
            startSelected = "selected=\"selected\"";
         }
         var endSelected = "";
         if (endTime.getTime() === calEvent.end.getTime()) {
            endSelected = "selected=\"selected\"";
         }
         $startTimeField.append("<option value=\"" + startTime + "\" " + startSelected + ">" + timeslotTimes[i].startFormatted + "</option>");
         $endTimeField.append("<option value=\"" + endTime + "\" " + endSelected + ">" + timeslotTimes[i].endFormatted + "</option>");

         $timestampsOfOptions.start[timeslotTimes[i].startFormatted] = startTime.getTime();
         $timestampsOfOptions.end[timeslotTimes[i].endFormatted] = endTime.getTime();

      }
      $endTimeOptions = $endTimeField.find("option");
      $startTimeField.trigger("change");
   }

   var $endTimeField = $("select[name='end']");
   var $endTimeOptions = $endTimeField.find("option");
   var $timestampsOfOptions = {start:[],end:[]};

   //reduces the end time options to be only after the start time options.
   $("select[name='start']").change(function() {
      var startTime = $timestampsOfOptions.start[$(this).find(":selected").text()];
      var currentEndTime = $endTimeField.find("option:selected").val();
      $endTimeField.html(
            $endTimeOptions.filter(function() {
               return startTime < $timestampsOfOptions.end[$(this).text()];
            })
            );

      var endTimeSelected = false;
      $endTimeField.find("option").each(function() {
         if ($(this).val() === currentEndTime) {
            $(this).attr("selected", "selected");
            endTimeSelected = true;
            return false;
         }
      });

      if (!endTimeSelected) {
         //automatically select an end date 2 slots away.
         $endTimeField.find("option:eq(1)").attr("selected", "selected");
      }

   });


   var $about = $("#about");

   $("#about_button").click(function() {
      $about.dialog({
         title: "预约功能说明",
         width: 600,
         close: function() {
            $about.dialog("destroy");
            $about.hide();
         },
         buttons: {
            "关闭" : function() {
               $about.dialog("close");
            }
         }
      }).show();
   });

   var $login = $("#login");

   $("#login_button").click(function() {
	   if($(this).data("isLogin"))
	   {
		   //如果已经登录了,再点击就退出
		   $("#login_button span").html("登录");	
		   $("#clear_button,#allbook_button,#test_button,#load_button").hide();
		   //重新更改字
		   $("#logintime").html("");
		　　　$("#usertype").html("游客")
		   $(this).data("isLogin",false);
		   
		   //设置登录部门号为0
		   $(this).data("duty",0);
		   
		   //重新刷新视图
		   $("#calendar").weekCalendar("refresh");
	   }
	   else{
		  $("#error").hide();
	      $login.dialog({
	         title: "登 录",
	         width: 400,
			 resizable:false,
	         close: function() {
	            $login.dialog("destroy");
	            $login.hide();
	         },
	         buttons: {
				"登录" : function(){
					//隐藏错误
					$("#error").hide();
					//客户端验证
					var name=$("#username").val();
					var psword=$("#password").val();
					//正则表达式
					b=/^[a-zA-Z\d]\w{3,13}[a-zA-Z\d]$/;
					if(!b.test(name))
					{
						$("#error").html("错误：用户名应当为5~15个英文（数字）单词").show(1000);
						return false;
					}
					
					if(!b.test(psword))
					{
						$("#error").html("错误：密码应当为5~15个英文单词").show(1000);
						return false;
					}				
					//ajax请求，服务器验证
					var data='action=login&username='+name+"&password="+psword+"&tbname=user";
			 
					 $.ajax({
						 type:"POST",
						 url:"action/login.php",
						 data:data,
						 success:function(data)
						 {
							 if(data=="false")
							 {
								 $("#error").html("错误：用户名或密码错误！").show(1000);
							 }
							 else
							 {
								 //解析json
								var user=eval("("+data+")");
							 	$("#logintime").html("上次登录时间："+user.time);
								$("#usertype").html("管理员："+user.username);				
								//将部门号记录下来
								$("#login_button").data("duty",user.duty);
								
								//同时关闭对话框
								$login.dialog("close");
								$("#clear_button,#allbook_button,#test_button,#load_button").show();
								$("#login_button").data("isLogin",true);
								$("#login_button span").html("退出");
								
								//更新视图
			  					$("#calendar").weekCalendar("refresh");
																				
							 }
						 }
						 
					});	
					
				},
				"重置" : function(){				
					//清空输入框
					$("#login input").val("");
					//隐藏错误
					$("#error").hide();
				},
	            "关闭" : function() {               
				   //清空输入框
					$("#login input").val("");
					$login.dialog("close");
					if($("#login_button").data("isLogin"))
					{
						$("#login_button span").html("退出");
						$("#clear_button,#allbook_button,#test_button,#load_button").show();
					}
					else
					{
						$("#login_button span").html("登录");
						$("#clear_button,#allbook_button,#test_button,#load_button").hide();					
					}
					
	            }
	         }
	      }).show();
	   }
   });



   $("#load_button").click(function() {
	   //清空所有预约
      $("#calendar").weekCalendar("clear");
	  
	  
	  
		//与服务器通话，保持数据同步
		 talkWithServer("load",$("#selectRoom").data("tbname"),2,0,true,function(data){
				for(i=0;i<data.length;i++)
				{
					$("#calendar").weekCalendar("updateEvent",data[i]);
				}
		 });		 
   });


	$("#allbook_button").click(function(){
		
		var allBook=$("#calendar").weekCalendar("serializeEvents");
		html="";
		for(i=0;i<allBook.length;i++)
		{
			html+=allBook[i].title+"<br/>";
		}
		showInformation(html,timeIn,timeOut);	
	});
	
	$("#clear_button").click(function(){
		
		var info="  确定要清空所有预约？\n此操作不可逆，请慎重！";
		if(confirm(info))
		{
			//先在前端清空所有的预约
			$("#calendar").weekCalendar("clear");
			id=1;
			//与服务器通话，保持数据同步
			 talkWithServer("deleteall",$("#selectRoom").data("tbname"),2,0,true,function(data){
					showInformation(data,timeIn,timeOut);
			 });
		}
		else
		{
			showInformation("你已经取消了删除操作",timeIn,timeOut);			
		}
			
	});




	/**
		初始化数据，当刚进入页面或者切换视图时
		从数据库中获取预约数据
	*/
	function initEventData()
	{
		
		//与服务器通话，由于要等数据到达，所以需要同步，让async为false
		 talkWithServer("load",$("#selectRoom").data("tbname"),2,0,false,function(data){
				var dataArr=new Array();
				
				for(i=0;i<data.length;i++)
				{
					dataArr[i]=data[i];
				}
				//将数据存储到某个选择器上
				$("#calendar").data("initData",{events:dataArr});
		 });
	}	
	
	function getMaxID()
	{
		//获取数据
		getCurrentMaxID();
		var maxid=$("#calendar").data("maxID");
		maxid=Number(maxid)+1;
		return maxid
	}
	
	function getCurrentMaxID()
	{
		//与服务器通话，获取当前最大ID号，注意不能使用异步，否则保存的数据会不存在——因为先执行了success函数
		 talkWithServer("maxID",$("#selectRoom").data("tbname"),2,0,false,function(data){
				$("#calendar").data("maxID",data);
		});		
	}

	function talkWithServer(action,tbname,duty,data,isasync,func)
	{
		 jsondata='action='+action+"&duty="+duty+"&data="+data+"&tbname="+tbname;
		 
		 $.ajax({
			 type:"POST",
			 url:"action/deal.php",
			 async:isasync,
			 data:jsondata,
			 success:function(data)
			 {
				 func(data);
			 }
			 
		});	
	}

	//显示提示
	function showInformation(msg,timeIn,timeOut)
	{
		$("#show").html(msg).fadeIn(timeIn);
	}

	//从服务器上获取所有表名，同时初始化下拉框
	function initSelect()
	{
		//获取所有表名
		talkWithServer("showTables",0,2,0,false,function(data){
				var str="";
				//将简单JSON通过eval函数转换成JS中的数组
				names=eval(data);
				
				//先清空原来的下拉框内容
				$("#selectRoom").empty();
				
				for(var i=0; i<names.length;i++)
				{
					$("<option value='"+names[i]+"'>"+names[i]+"</option>").appendTo("#selectRoom");					
				}
				showInformation("成功初始化教室列表",timeIn,timeOut);
		});

	}
	


});
